﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Pifagor.IG;
using Pifagor.Exceptions;

namespace Pifagor.Runtime
{
	public class DataList : IComputableValue
	{
		ExecutionContext _context;
		IGNode _dataListNode;
		Value _value;

		public Value[] Items { get; private set; }

		internal DataList(ExecutionContext context, IGNode dataListNode)
		{
			_context = context;
			_dataListNode = dataListNode;

			// data list is eagerly computed as soon as it is created.
			Compute();
		}

		public Value Compute()
		{
			if (_value == null)
			{
				Items = new Value[_dataListNode.Links.Length];
				for (int i = 0; i < _dataListNode.Links.Length; i++)
				{
					var listValueNodeLink = _dataListNode.Links[i];
					Items[i] = ComputableFactory.CreateComputable(_context, _context.IG.Nodes[listValueNodeLink.Id]).Compute();
				}
				_value = new Value(this);
			}

			return _value;
		}

		public override string ToString()
		{
			if (_value == null)
				throw new RuntimeException("DataList must be computed before one can display it.");

			return "(" + string.Join(", ", Items.Select(item => item.ToString()).ToArray()) + ")";
		}
	}
}
